//
//  TKIMImageBorwView.m
//  TKIM_Thinkive
//
//  Created by liupm on 16/4/15.
//  Copyright © 2016年 liupm. All rights reserved.
//

#import "TKIMImageBrowserView.h"
#import "TKIMProgressView.h"
#import "UIView+WebCacheOperation.h"

@interface TKIMImageBrowserView()<UIScrollViewDelegate,UIGestureRecognizerDelegate,UIActionSheetDelegate>
@property(nonatomic,strong) TKIMProgressView *progressView;
@property(nonatomic,strong) UIScrollView *scrollView;
@property(nonatomic,strong) UIImageView *imageView;
@property(nonatomic,strong) UIView *contentView;
@property(nonatomic,strong) UIView *fromView;
@property(nonatomic,strong) UIView *layerView;
@end

@implementation TKIMImageBrowserView

- (instancetype)initWithFrame:(CGRect)frame contentView:(UIView *)contentView
{
    self = [super initWithFrame:frame];
    if (self)
    {
        _contentView = contentView;
        [self drawView];
    }
    return self;
}

#pragma mark 方法

-(void)drawView
{
    [self addSubview:self.layerView];
    [self.scrollView addSubview:self.imageView];
    [self addSubview:self.scrollView];
    self.userInteractionEnabled = YES;
    //添加单击手势
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hide)];
    [self addGestureRecognizer:tap];
    //添加双击手势
    UITapGestureRecognizer *tap2 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(doubleTap:)];
    tap2.delegate = self;
    tap2.numberOfTapsRequired = 2;
    [tap requireGestureRecognizerToFail: tap2];
    [self addGestureRecognizer:tap2];
    
    UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPress:)];
    longPress.minimumPressDuration = 1;
    [self addGestureRecognizer:longPress];
    
}


/**
 *  @Author lpm, 16-04-20 15:04:05
 *
 *  @brief  展示
 *
 *  @param fromView 从哪个view来;
 */
-(void)show:(UIImageView *)fromView
{
    if (!fromView.image)
    {
        return;
    }
    _fromView = fromView;
    CGRect fromFrame = [_fromView convertRect:_fromView.bounds toView:_contentView];
    self.frame = fromFrame;
    CGFloat  scale = fromView.image.size.width/fromView.image.size.height;
    __weak typeof(self) weakSelf = self;
    self.scrollView.frame = CGRectMake(0, 0, fromFrame.size.width, fromFrame.size.height);
    self.layerView.frame = self.scrollView.frame;
    //重新设置imageView的长宽
    CGFloat imgHeight = weakSelf.scrollView.width/scale;
    self.imageView.frame = CGRectMake(0, (fromFrame.size.height- imgHeight)/2, fromFrame.size.width, imgHeight);
    self.imageView.image = fromView.image;
    [_contentView addSubview:self];
    
    //    self.alpha = 0.0;
    [UIView animateWithDuration:0.2 animations:^{
        //        weakSelf.alpha = 1.0;
        weakSelf.frame = CGRectMake(0, 0, _contentView.width, _contentView.height);
        weakSelf.scrollView.frame =CGRectMake(0, 0, self.width, self.height);
        weakSelf.layerView.frame = self.scrollView.frame;
        CGFloat imgHeight = weakSelf.scrollView.width/scale;
        weakSelf.imageView.frame = CGRectMake(0, (weakSelf.scrollView.height- imgHeight)/2, weakSelf.scrollView.width,imgHeight);
    } completion:^(BOOL finished) {
        [weakSelf loadImage];
    }];
}


/**
 *  @Author lpm, 16-04-20 14:04:27
 *
 *  @brief  隐藏
 */
-(void)hide
{
    if ([self.progressView superview])
    {
        [self.progressView removeFromSuperview ];
    }
    __weak typeof(self) weakSelf = self;
    CGRect fromFrame = [_fromView convertRect:_fromView.bounds toView:_contentView];
    //    self.alpha = 1.0;
    [UIView animateWithDuration:0.2 animations:^{
        //        weakSelf.alpha = 0.0;
        weakSelf.scrollView.frame = fromFrame;
        weakSelf.layerView.frame = self.scrollView.frame;
        weakSelf.imageView.frame = CGRectMake(0, 0, fromFrame.size.width, fromFrame.size.height);
    } completion:^(BOOL finished) {
        [self removeFromSuperview];
//        [self.imageView sd_cancelCurrentAnimationImagesLoad];
        [self.imageView sd_cancelImageLoadOperationWithKey:@"UIImageViewAnimationImages"];
    }];
}


/**
 *  @Author lpm, 16-04-20 16:04:30
 *
 *  @brief  双击放大
 *
 *  @param g
 */
- (void)doubleTap:(UITapGestureRecognizer *)g
{
    if (self.scrollView) {
        if (self.scrollView.zoomScale > 1)
        {
            [self.scrollView setZoomScale:1 animated:YES];
        }
        else
        {
            CGPoint touchPoint = [g locationInView:self.imageView];
            CGFloat newZoomScale = self.scrollView.maximumZoomScale;
            CGFloat xsize = self.width / newZoomScale;
            CGFloat ysize = self.height / newZoomScale;
            [self.scrollView zoomToRect:CGRectMake(touchPoint.x - xsize/2, touchPoint.y - ysize/2, xsize, ysize) animated:YES];
        }
    }
}

/**
 *  @Author lpm, 16-04-20 16:04:30
 *
 *  @brief  长按保存到本地
 *
 *  @param g
 */
- (void)longPress:(UILongPressGestureRecognizer *)g
{
    if (g.state == UIGestureRecognizerStateBegan)
    {
        UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"保存到相册", nil];
        [actionSheet showInView:self];
    }
}


/**
 *  @Author lpm, 16-05-04 17:05:07
 *
 *  @brief
 *
 *  @param actionSheet
 *  @param buttonIndex
 */
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if(buttonIndex == 0)
    {
        ALAssetsLibrary  *lib = [[ALAssetsLibrary alloc] init];
        UIImage *img = self.imageView.image;
        [lib writeImageToSavedPhotosAlbum:img.CGImage metadata:nil completionBlock:^(NSURL *assetURL, NSError *error) {
            if (!error)
            {
                UIAlertView *alert  = [[UIAlertView alloc] initWithTitle:@"保存成功" message:nil delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                [alert show];
            }
        }];
    }
}
#pragma mark scrollview代理
/**
 *  @Author lpm, 16-04-20 16:04:24
 *
 *  @brief  返回缩放的是哪个ImageView
 *
 *  @param scrollView
 *
 *  @return
 */
-(UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView{
    return self.imageView;
}

/**
 *  @Author lpm, 16-04-20 16:04:35
 *
 *  @brief  实现图片在缩放过程中居中
 *
 *  @param scrollView
 */
- (void)scrollViewDidZoom:(UIScrollView *)scrollView
{
    CGFloat offsetX = (scrollView.bounds.size.width > scrollView.contentSize.width)?(scrollView.bounds.size.width - scrollView.contentSize.width)/2 : 0.0;
    CGFloat offsetY = (scrollView.bounds.size.height > scrollView.contentSize.height)?(scrollView.bounds.size.height - scrollView.contentSize.height)/2 : 0.0;
    self.imageView.center = CGPointMake(scrollView.contentSize.width/2 + offsetX,scrollView.contentSize.height/2 + offsetY);
}

#pragma mark 系统方法重写

-(void)loadImage
{
    __weak typeof(self) weakSelf = self;
    //图片的长宽比例
    __block CGFloat scale = 0;
    //如果原图有值
    if (_orgImage)
    {
        scale = _orgImage.size.width/_orgImage.size.height;
        self.imageView.image = _orgImage;
    }
    else
    {
        //如果缩略图有值
        if(_thubImage)
        {
            scale = _thubImage.size.width/_thubImage.size.height;
            self.imageView.image = _thubImage;
        }
        //网络图片地址
        NSURL *imageUrl;
        //如果原图地址不为空
        if (![TKIMStringHelper isEmpty:_orgImagUrl])
        {
            imageUrl = [NSURL URLWithString:_orgImagUrl];
        }
        //如果缩略图的地址不为空
        else if (![TKIMStringHelper isEmpty:_thubImageUrl])
        {
            imageUrl = [NSURL URLWithString:_thubImageUrl];
        }
        
        //网络地址存在
        if (imageUrl)
        {
            self.progressView.center = self.center;
            if (![self.progressView superview])
            {
                [self addSubview:self.progressView];
            }
//            [self.imageView sd_setImageWithPreviousCachedImageWithURL:imageUrl placeholderImage:self.imageView.image options:0 progress:^(NSInteger receivedSize, NSInteger expectedSize, NSURL * _Nullable targetURL) {
//                CGFloat pro = (float)receivedSize/expectedSize;
//                weakSelf.progressView.progress = pro;
//            } completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
//                if ([self.progressView superview])
//                {
//                    [self.progressView removeFromSuperview ];
//                }
//                if (!error)
//                {
//                    scale = image.size.width/image.size.height;
//                    //重新设置imageView的长宽
//                    CGFloat imgHeight = weakSelf.scrollView.width/scale;
//                    weakSelf.imageView.frame = CGRectMake(0, (weakSelf.scrollView.height- imgHeight)/2, weakSelf.scrollView.width,imgHeight);
//                }
//            }];
            
            [self.imageView sd_setImageWithURL:imageUrl placeholderImage:self.imageView.image options:0 progress:^(NSInteger receivedSize, NSInteger expectedSize, NSURL * _Nullable targetURL) {
                CGFloat pro = (float)receivedSize/expectedSize;
                weakSelf.progressView.progress = pro;
            } completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
                if ([self.progressView superview])
                {
                    [self.progressView removeFromSuperview ];
                }
                if (!error)
                {
                    scale = image.size.width/image.size.height;
                    //重新设置imageView的长宽
                    CGFloat imgHeight = weakSelf.scrollView.width/scale;
                    weakSelf.imageView.frame = CGRectMake(0, (weakSelf.scrollView.height- imgHeight)/2, weakSelf.scrollView.width,imgHeight);
                }
            }];
        }
    }
    
    //如果长宽存在
    if(scale)
    {
        //重新设置imageView的长宽
        CGFloat imgHeight = weakSelf.scrollView.width/scale;
        weakSelf.imageView.frame = CGRectMake(0, (weakSelf.scrollView.height- imgHeight)/2, weakSelf.scrollView.width,imgHeight);
    }
}

#pragma mark 属性

-(UIScrollView *)scrollView
{
    if (!_scrollView)
    {
        _scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, self.width, self.height)];
        _scrollView.backgroundColor = [UIColor clearColor];
        _scrollView.contentSize = _scrollView.frame.size;
        _scrollView.delegate = self;
        //开启多点触摸
        _scrollView.multipleTouchEnabled = YES;
        //设置最小缩放比例
        _scrollView.minimumZoomScale = 1.0;
        //设置最大缩放比例
        _scrollView.maximumZoomScale = 2.0;
    }
    return _scrollView;
}


-(UIImageView *)imageView
{
    if (!_imageView)
    {
        _imageView = [[UIImageView alloc] init];
        _imageView.backgroundColor = [UIColor clearColor];
    }
    return _imageView;
}


-(TKIMProgressView *)progressView
{
    if (!_progressView)
    {
        _progressView = [[TKIMProgressView alloc] initWithFrame:CGRectMake(0, 0, 50, 50)];
        _progressView.type = TKIMProgressViewTypeCircle;
    }
    return _progressView;
}


-(UIView *)layerView
{
    if (!_layerView)
    {
        _layerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, _contentView.width, _contentView.height)];
        _layerView.backgroundColor = [UIColor blackColor];
        _layerView.alpha = 1.0;
    }
    return _layerView;
}
@end
